import { ElMessageBox, ElMessage } from "element-plus";
import { HandleData } from "./interface";

/**
 * @description 操作单条数据信息(二次确认【删除、禁用、启用、重置密码】)
 * @param {Function} api 操作数据接口的api方法(必传)
 * @param {Object} params 携带的操作数据参数 {id,params}(必传)
 * @param {String} message 提示信息(必传)
 * @param {String} confirmType icon类型(不必传,默认为 warning)
 * @return Promise
 */
export const useHandleData = (api: (params: any) => Promise<any>,params: any,message: string,confirmType: HandleData.MessageType = "warning") => {
	return new Promise((resolve, reject) => {
		ElMessageBox({
            title: '温馨提示',
            dangerouslyUseHTMLString: true,
            message: `是否${message}?`,
            type: confirmType,
            showCancelButton: true,
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            beforeClose: async (action, instance, done) => {
                if (action === 'confirm') {
                    instance.confirmButtonLoading = true
                    instance.confirmButtonText = '请求中...'
                    const res = await api(params);
                    done()
                    setTimeout(() => {
                        instance.confirmButtonLoading = false
                        instance.confirmButtonText = '确定'
                    }, 300)
                    if(res && res.code === 0) {
                        ElMessage({
                            type: "success",
                            dangerouslyUseHTMLString: true,
                            message: `${message}成功!`
                        });
                    }
                    resolve(res)
                } else {
                    done()
                    resolve(null)
                }
            }
        });
	});
};
